package com.ctvit.common;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringTrans {

	public static Pattern P_NUMBER = Pattern.compile("[0-9]*");            //只是数字
	public static Pattern P_CRLF = Pattern.compile("(\r\n|\r|\n|\n\r)");     //四种不同的回车

	/**
	 * 替换特殊符号
	 */
	public static String TransactSQLInjection(String str) {
		return str.replaceAll(".*([';]+|(--)+).*", " ");
	}

	/**
	 * 检查是不是纯数字
	 */
	public static boolean isNumber(String str) {
		return P_NUMBER.matcher(str).matches();
	}

	/**
	 * bigdec小数位转化
	 */
	public static String bigDecimalToString(BigDecimal bd, int digits) {
		if (digits < 0) {
			return "error";
		}
		return String.valueOf(bd.setScale(digits, BigDecimal.ROUND_HALF_UP)
				.doubleValue());
	}

	/**
	 * 判断某个字符串是否存在于数组中
	 *
	 * @param stringArray 原数组
	 * @param source      查找的字符串
	 * @return 是否找到
	 * @author zzj          http://bbs.csdn.net/topics/100171639
	 */
	public static boolean contains(String[] stringArray, String source) {
		//转换为list
		List<String> tempList = Arrays.asList(stringArray);

		//利用list的包含方法，进行判断
		if (tempList.contains(source)) {
			return true;
		}
		return false;
	}

	/**
	 * 替换四种不同的回车
	 * Pattern.compile("(\r\n|\r|\n|\n\r)");
	 *
	 * @param source
	 * @param replacement
	 * @return
	 */
	public static String replaceAllCRLF(String source, String replacement) {
		Matcher matcher = P_CRLF.matcher(source);
		String newString;
		if (matcher.find()) {
			newString = matcher.replaceAll(replacement);
		} else {
			newString = source;
		}
		return newString;
	}

	/**
	 * http://ipc.iteye.com/blog/1688385
	 * byte(字节)根据长度转成kb(千字节)和mb(兆字节)
	 *
	 * @param bytes
	 * @return
	 */
	public static String bytes2kb(long bytes) {
		BigDecimal filesize = new BigDecimal(bytes);
		BigDecimal megabyte = new BigDecimal(1024 * 1024);
		float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
				.floatValue();
		if (returnValue >= 1) {
			return (returnValue + "MB");
		}
		BigDecimal kilobyte = new BigDecimal(1024);
		returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
				.floatValue();
		return (returnValue + "KB");
	}
}
